package com.lzx.adx.report.controller.v1.qtt;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.redis.RedisUtils;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.constant.RedisCacheKey;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.model.qtt.QttRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.AdPerUtil;
import com.lzx.adx.report.util.DynamicRequestLimiter;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import com.lzx.adx.report.util.UrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 产品：万维-当当
 * 媒体：趣头条
 */
@RequestMapping("/qtt/wangwei")
@RestController
@Slf4j
public class QttWanWeiController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private DynamicRequestLimiter dynamicRequestLimiter;


    @Autowired
    private RedisUtils redisUtils;




    @GetMapping("/report")
    public ResponseEntity report(QttRequest requestParams, HttpServletRequest request) {
        log.info("接收到趣头条到万唯当当的点击请求参数为{}", JsonUtils.toJsonString(requestParams));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(requestParams);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(requestParams));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        reportDTO.setImeiSum(requestParams.getImei());
        reportDTO.setOaidSum(requestParams.getOaidMd5());


        AccountDTO accountDTO = AccountLocalCache.getInstance().get(requestParams.getDspId());
        JSONObject jsonObject = JSONObject.parseObject(accountDTO.getSspExtend());

        ResponseEntity<Result> ok =dynamicRequestLimiter.getResultResponseEntity(jsonObject, reportDTO);
        if (ok != null) return ok;

        //通过的
        redisUtils.addToList(RedisCacheKey.qtt_oneway_callback, reportDTO.getBizRequestId());


        return ResponseEntity.ok(new Result());
    }




    /**
     * 万唯当当的回传
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/callback")
    public ResponseEntity alCallBackUrl(String requestId,String eventType) {
        log.info("万维当当回调趣头条信息，请求流水号{},回调类型为{}", requestId, eventType);
        if (StringUtils.isBlank(requestId)||StringUtils.isBlank(eventType)) {
            log.info("万维当当回调趣头条信息参数异常");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        long currentTimeMillis = System.currentTimeMillis();
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
        } else {
            log.error("当前流水号{}，系统当前不存在", requestId);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String transformType = jsonObject.getString(eventType);
        if (StringUtils.isBlank(transformType)){
            log.info("万维当当回调趣头条信息当前流水号：{}，事件类型{}不合法，不做数据回传", requestId,eventType);
            return ResponseEntity.ok(new Result());
        }
        reportDTO.setResultType(eventType);
        reportDTO.setResultTime(String.valueOf(currentTimeMillis));
        reportDTO.setUpdateTime(new Date());
        reportService.updateData(reportDTO,eventType);
        Double per = jsonObject.getDouble("per");
        if (Objects.nonNull(per)) {
            if(!AdPerUtil.randomPer(per)) {
                log.info("账户{}流水号{}超出了比例,不做回传", reportDTO.getDspId(), reportDTO.getBizRequestId());
                return ResponseEntity.ok(new Result());
            }
        }
        //3，获取回传地址，进行解码
        String decodeUrl = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        //拼接完整的请求参数
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("op2", transformType);
        paramsReq.put("opt_active_time", currentTimeMillis / 1000);
        String finalUrl = decodeUrl + "&" + URLUtil.buildQuery(paramsReq, StandardCharsets.UTF_8);
        log.info("请求流水号{}万维当当回调趣头条的完整地址为：{}", requestId, finalUrl);
        String result = HttpUtil.get(finalUrl);
        log.info("请求流水号{}万维当当回调趣头条的结果为：{}", requestId, result);
        return ResponseEntity.ok(new Result());
    }

    

}
